import axios, { InternalAxiosRequestConfig, AxiosResponse } from 'axios'
import { nextTick } from 'vue'
import {ElMessage} from "element-plus";
import { getToken } from '@/utils/auth';
import router from "../router";

const request = axios.create({
	withCredentials: true,
	baseURL: import.meta.env.VITE_ADMIN_URL,
	timeout: 30000,
})

const token = getToken() // 获取token

// 请求拦截器
request.interceptors.request.use(
	(config: InternalAxiosRequestConfig) => {
		if (!token) {
		}
		config.headers['Authorization'] = 'Bearer ' + getToken()
		// console.log(config.headers)

		return config
	},
	(error) => {
		console.log(error)
		return Promise.reject(error)
	},
)

// 响应拦截器
request.interceptors.response.use(
	(response: AxiosResponse) => {
		return response
	},
	(error) => {
		const data = error.response.data
		const status = error.response.status
		console.log("data=====", error.response)
		// 对不同状态码进行管理
		if (status === 401) {
			localStorage.removeItem('token');
            router.push('/login');
			console.log('登录已过期')
		} else if (status === 500) {
			console.log('服务器错误')
		} else {
			console.log('请求错误状态码:', status)
		}
		ElMessage.error(error.response?.data?.message);
		return Promise.reject()
	},
)

export default request
